package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.RestFo.RestBean;
import com.example.demo.RestFo.RestPage;
import com.example.demo.entity.Mydog;
import com.example.demo.service.MydogService;
import com.example.demo.service.impl.MydogServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.websocket.server.PathParam;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hpp
 * @since 2021-09-27
 */
@RestController
//@RequestMapping("")
public class MydogController {
    @Autowired
    MydogServiceImpl mydogService;
    /*上传人脸图像*/
    @CrossOrigin
    @PostMapping("/pics")
    public RestBean<String> addPic( @RequestParam("file") MultipartFile file) throws Exception{
        String folder= "D:\\zhushou\\image";
        File imageFolder = new File(folder);
        /*如果不存在该路径则创建*/
        if(!imageFolder.exists()){
            imageFolder.mkdirs();
        }
        /*使用唯一的名字命名图片名称*/
        String uniName = UUID.randomUUID() + file.getOriginalFilename();
        String fullName = folder +'/' + uniName;
        File f = new File(fullName);
        /*将前端传来的文件保存到相应的路径中*/
        try {
            file.transferTo(f);
            System.out.println(f.getAbsolutePath() + "保存成功！");
            String nameUrl = "http://localhost:8082/api/file/" + uniName;
            return new RestBean<String>(200,"success",nameUrl,"");
        }catch(IllegalStateException e){
            e.printStackTrace();
        }catch(IOException el){
            el.printStackTrace();
        }
        /*添加失败或者遇到异常返回*/
        return new RestBean<>(0,"error",null,"");
    }

    /*添加学生信息*/
    @CrossOrigin
    @PostMapping("/addStudent")
    public RestBean<Mydog> addStudentInfo(@RequestParam("number") int number,
                                          @RequestParam("name") String name,
                                          @RequestParam("url") String url){
        Mydog mydog = new Mydog();
        mydog.setNumber(number);
        mydog.setName(name);
        mydog.setUrl(url);
        boolean save = mydogService.save(mydog);
        if(save){
            /*添加成功返回*/
            return new RestBean<>(200,"success",mydog,"");
        }
        /*添加失败或者遇到异常返回*/
        return new RestBean<>(0,"error",null,"");
    }
//    /*根据学号更新学生的信息:姓名和人脸图片*/
//    @CrossOrigin
//    @PutMapping("")
//    public RestBean<Mydog> modifyInfoByNumber(@RequestParam("number") int number,
//                                       @RequestParam("name") String name,
//                                       @RequestParam("file") MultipartFile file) {
//        String folder = "D:\\zhushou\\image";
//        File ffolder = new File(folder);
//        /*如果存储路径不存在则新建文件夹*/
//        if (!ffolder.exists()) {
//            ffolder.mkdirs();
//        }
//        /*唯一的图像名称,获得绝对路径*/
//        String fullname = folder + "\\" + UUID.randomUUID() + file.getOriginalFilename();
//        File f = new File(fullname);
//        try {
//            file.transferTo(f);
//            System.out.println("成功保存！");
//            /*根据学号返回学生信息并删除原来硬盘中的图片*/
//            QueryWrapper<Mydog> wrapper = new QueryWrapper<>();
//            wrapper.eq("number", number);
//            Mydog one = mydogService.getOne(wrapper);
//            String url = one.getUrl();
//            File myDelFile = new File(url);
//            boolean delete = myDelFile.delete();
//            if (delete) {
//                System.out.println("原图片删除成功！");
//            }
//            Integer id = one.getId();
//            UpdateWrapper<Mydog> upWrapper = new UpdateWrapper<>();
//            upWrapper.eq("id", id).set("name", name).set("url", fullname);
//            boolean update = mydogService.update(upWrapper);
//            Mydog byId = mydogService.getById(id);
//            if (update) {
//                return new RestBean<>(200, "success", byId, "");
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch(IllegalStateException el){
//            el.printStackTrace();
//        }
//        return new RestBean<>(0, "error", null, "");
//    }
    /*根据id序号获取一个学生信息和其他三个随机的学生信息*/
    /*@CrossOrigin
    @GetMapping("/random")
    public RestBean<List<Mydog>> getRandomPic(@RequestParam("pagesize") int pagesize,
                                 @RequestParam("pagenum") int pagenum) {
        IPage<Mydog> page = new Page<>(pagenum,pagesize);
        IPage<Mydog> page1 = mydogService.page(page);
        List<Mydog> records = page1.getRecords();
//        double random = Math.random();
//        int ran= (int)random*pagesize;
//        Mydog mydog = records.get(ran);
        return new RestBean<>(200,"success",records,"");
    }*/
    /*根据id序号获取一个学生信息和其他三个随机的学生信息*/
    @CrossOrigin
    @GetMapping("/random")
    public RestBean<RestPage<Mydog>> getRandomPic(@RequestParam("id") int id) {
        /*查询总记录数*/
        int total = mydogService.count();
        System.out.println(total);
        /*在total范围内随机选三个不同的Id号*/
        Set<Integer> mySet=new HashSet<Integer>();
        /*先将请求id加入到hashset中，以免重复*/
        mySet.add(id);
        while(mySet.size()<=3) {
            mySet.add((int)(Math.random()*total)+1);
        }
        System.out.println(mySet.size());
        List<Integer> ls=Arrays.asList(mySet.toArray(new Integer[0]));
        Collections.shuffle(ls);
        List<Mydog> mydogs = new ArrayList<>();
        /*根据id查询，并查看四个随机数是否相同*/
        for (Integer l : ls) {
            /*根据id查询*/
            Mydog byId = mydogService.getById(l);
            mydogs.add(byId);
            System.out.println(l);
        }
        RestPage<Mydog> myPage = new RestPage<>(total,mydogs);
        return new RestBean<>(200,"success",myPage,"");
    }
    /*根据id获取学生人脸信息*/
    @CrossOrigin
    @GetMapping("/getStudent/id")
    public RestBean<Mydog> getInfoById(@RequestParam("id") int id){
        Mydog byId = mydogService.getById(id);
        return new RestBean<>(200,"success",byId,"");
    }
    /*根据学号获取学生信息*/
    @CrossOrigin
    @GetMapping("/getStudent/number")
    public RestBean<Mydog> getInfoByNumber(@RequestParam("number") int number){
        QueryWrapper<Mydog> queryW = new QueryWrapper<>();
        queryW.eq("number",number);
        Mydog byId = mydogService.getOne(queryW);
        return new RestBean<>(200,"success",byId,"");
    }
    /*根据id删除学生信息*/
    @CrossOrigin
    @DeleteMapping("/deleteStudent/id")
    public RestBean<Mydog> deleteInfoById(@RequestParam("id") int id){
        boolean b = mydogService.removeById(id);
        /*删除成功*/
        if(b){
            return new RestBean<>(200,"success",null,"");
        }
        return new RestBean<>(0,"error",null,"");
    }
    /*根据学号删除学生信息*/
    @CrossOrigin
    @DeleteMapping("/deleteStudent/number")
    public RestBean<Mydog> deleteInfoByNumber(@RequestParam("number") int number){
        QueryWrapper<Mydog> queryW = new QueryWrapper<>();
        queryW.eq("number",number);
        boolean remove = mydogService.remove(queryW);
        /*删除成功*/
        if(remove){
            return new RestBean<>(200,"success",null,"");
        }
        return new RestBean<>(0,"error",null,"");
    }
}

